#include "client.h"
#define MAXSIZE 1024

int main(int argc,char* argv[])
{
    //创建客户端套接字
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    if (clientfd == -1) {
        error(1, errno, "socket");
    }

    //服务端网络地址
    struct sockaddr_in serveraddr;
    socklen_t len = sizeof(serveraddr);
    memset(&serveraddr, 0, len);
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(8080);
    serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    int ret = connect(clientfd, (const struct sockaddr*)&serveraddr, len);
    if (ret == -1) {
        error(1, errno, "connect");
    }
    
    int error_time = 0;
    login(clientfd,&error_time);
    const char* commands[8] = {     // 字符串数组
        "pwd",
        "ls",
        "cd",
        "mkdir",
        "rmdir",
        "puts",
        "gets",
        "tree"
    };
    showmenu();
    //执行命令
    while (1) {
        //创建一个任务类型
        client_task_t task;
        memset(&task,0,sizeof(task));
        task.peerfd  = clientfd;
    //初始化client端的任务client_task_t
        char buff[MAXSIZE] = {0};
        //fgets(buff, MAXSIZE, stdin);
        read(STDIN_FILENO, buff, MAXSIZE);
        //命令格式为：如cd dir
        char *bufhead = NULL,*bufbody = NULL;
        parseInput(buff, &bufhead, &bufbody);
        for(int i =0;bufbody && bufbody[i]!='\0';i++){
            task.train.buff[i] = bufbody[i];
        }
        // 遍历字符串数组并比较
        int i;
        for (i = 0; i < 8; i++) {
            if (strcmp(commands[i], bufhead) == 0) {
                task.train.type = (CmdType)(i + 1);
                break;
            }
        }
        // 如果循环结束后还没有找到匹配项，说明输入的错误的命令
        if (i == 8) {
            task.train.type = CMD_TYPE_NOTCMD;
        }
    //处理不同的任务类型
        //将命令发送服务端
        task.train.len = strlen(task.train.buff);
        int ret = sendn(task.peerfd, &task.train, 4 + 4 + task.train.len);
        if (ret == -1) {//出错
            break;
        }
        doTask(&task);
        //接收操作的结果
        //采用switch来对上述命令进行后续操作
    }//while

    return 0;
}

